<template>
  <div class="home-container">
    <!-- 顶部导航栏 -->
    <TopBar
      :user-display-name="userStore.userDisplayName"
      :is-authenticated="userStore.isAuthenticated"
      @logout="handleLogout"
      @login="goToLogin"
    />

    <div class="main-layout">
      <!-- 左侧边栏 -->
      <div class="left-sidebar">
        <!-- 个人信息区域 -->
        <UserInfoCard
          :user-display-name="userStore.userDisplayName"
          :is-authenticated="userStore.isAuthenticated"
          :avatar-url="avatarUrl"
          :level="userLevel"
          :title="userTitle"
        />

        <!-- 房间操作按钮区域 -->
        <RoomActionButtons
          @create-room="showCreateRoom = true"
          @join-room="showJoinRoom = true"
        />

        <!-- 音乐控制区域 -->
        <MusicController />
        

      </div>

      <!-- 右侧主内容区域 -->
      <div class="main-content">
        <div class="content-header">
          <div class="title-and-search">
            <h2 class="content-title">所有房间信息</h2>
            <div class="search-wrap">
              <SearchInput v-model="searchQuery" />
            </div>
          </div>
          <div class="header-actions">
            <div class="stat-pill rooms" title="当前房间数量">
              <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                <rect x="3" y="3" width="7" height="7" rx="1"/>
                <rect x="14" y="3" width="7" height="7" rx="1"/>
                <rect x="14" y="14" width="7" height="7" rx="1"/>
                <rect x="3" y="14" width="7" height="7" rx="1"/>
              </svg>
              <span class="label">房间</span>
              <span class="value">{{ roomsCount }}</span>
            </div>
            <div class="stat-pill players" title="全部玩家总数">
              <svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                <path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/>
                <circle cx="12" cy="7" r="4"/>
              </svg>
              <span class="label">玩家</span>
              <span class="value">{{ totalPlayers }}</span>
            </div>
            <button class="refresh-btn" @click="loadRooms" :disabled="roomStore.loading" title="刷新房间列表" aria-label="刷新">
              <svg class="refresh-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
                <path d="M21 12a9 9 0 0 0-15.5-6.364M3 12a9 9 0 0 0 15.5 6.364"/>
                <path d="M7 5H3V1M17 23h4v-4"/>
              </svg>
            </button>
          </div>
        </div>
        
        <!-- 房间列表（重做布局） -->
        <div class="grid-wrap">
          <RoomGrid
            :rooms="filteredRooms"
            :loading="roomStore.loading"
            :search-query="searchQuery"
            @select-room="enterRoomFromCard"
            @join-room="enterRoomFromCard"
          />
        </div>
        <div v-if="!roomStore.currentRoom" class="hint-box" role="note" aria-live="polite">
          <div class="hint-icon" aria-hidden="true">
            <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
          </div>
          <div class="hint-content">
            <div class="hint-title">小提示</div>
            <div class="hint-text">点击房间卡片即可查看并进入准备界面</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 创建房间弹窗 -->
    <CreateRoomDialog
      :visible="showCreateRoom"
      @close="showCreateRoom = false"
      @room-created="handleRoomCreated"
    />

    <!-- 加入房间弹窗（保留输入ID入口） -->
    <JoinRoomDialog
      :visible="showJoinRoom"
      :initial-room-id="pendingJoinRoomId"
      :mock="false"
      @close="() => { showJoinRoom = false; pendingJoinRoomId = '' }"
      @room-joined="handleRoomJoined"
    />

    <!-- 房间信息弹窗移除：信息并入成员弹窗 -->

    <!-- 房间成员弹窗 -->
    <RoomMembersDialog
      :visible="showRoomMembers"
      :room="currentRoom"
      :mock="true"
      @close="showRoomMembers = false"
      @game-started="handleGameStarted"
    />
  </div>
</template>

<script setup>
// 页面职责：
// - 展示房间列表（从API获取真实数据），支持搜索与刷新
// - 处理创建/加入/查看房间信息的弹窗交互
// - 在用户加入/创建房间后，导航至游戏页或显示成员信息
import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
import { ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useRoomStore } from '../stores/room'
import socketManager from '@/utils/socket'
import CreateRoomDialog from '@/components/rooms/dialogs/CreateRoomDialog.vue'
import JoinRoomDialog from '@/components/rooms/dialogs/JoinRoomDialog.vue'
import RoomMembersDialog from '@/components/rooms/dialogs/RoomMembersDialog.vue'
import TopBar from '@/components/layout/TopBar.vue'
import UserInfoCard from '@/components/user/UserInfoCard.vue'
import RoomActionButtons from '@/components/rooms/RoomActionButtons.vue'
import SearchInput from '@/components/rooms/SearchInput.vue'
import MusicController from '@/components/audio/MusicController.vue'
// RoomStats 统计条已并入 header 内，不再单独引入
import RoomGrid from '@/components/rooms/RoomGrid.vue'
import request from '@/utils/request.js'
import { userLevelAPI } from '@/api'
import { handleApiResponse } from '@/utils/request.js'

const router = useRouter()
const userStore = useUserStore()
const roomStore = useRoomStore()

// 环境开关：是否启用等级系统接口（强制开启）
const enableUserLevel = true

// 简单 JWT 解码（与 store 保持一致）
const decodeJwt = (token) => {
  try {
    const payload = token.split('.')[1]
    const json = decodeURIComponent(atob(payload.replace(/-/g, '+').replace(/_/g, '/')).split('').map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2)).join(''))
    return JSON.parse(json)
  } catch { return null }
}

// 头像渲染地址
const avatarUrl = ref('')
const avatarObjectUrl = '' // 保留以兼容旧逻辑，当前未使用

const loadAvatarUrl = async () => {
  try {
    const fileName = userStore.user?.avatar
    if (!fileName) {
      avatarUrl.value = ''
      return
    }
    if (typeof fileName === 'string' && (fileName.startsWith('http://') || fileName.startsWith('https://'))) {
      avatarUrl.value = fileName
      return
    }
    // 避免扩展读取 blob 导致控制台报错，改为直链 URL 方式
    const base = (request?.defaults?.baseURL || '').replace(/\/+$/, '')
    const safe = encodeURIComponent(fileName)
    avatarUrl.value = `${base}/users/avatar-file/${safe}`
  } catch (e) {
    avatarUrl.value = ''
  }
}

// 等级与称号
const userLevel = ref('')
const userTitle = ref('')

const loadUserLevel = async () => {
  if (!enableUserLevel) return
  try {
    let uid = userStore.user?.id
    if (!uid) {
      const tokenStr = localStorage.getItem('token')
      const tokenObj = tokenStr ? (()=>{ try{return JSON.parse(tokenStr)}catch{return null} })() : null
      const accessToken = tokenObj?.accessToken
      const payload = accessToken ? decodeJwt(accessToken) : null
      uid = payload?.uid || payload?.user_id || payload?.userId || payload?.sub
    }
    if (!uid) return

    // 获取等级信息（标准响应：{code, message, data}）
    const levelRes = await userLevelAPI.getUserLevel(uid, { meta: { silent: true } })
    const levelData = handleApiResponse(levelRes, 'data')
    userLevel.value = levelData?.currentLevel ?? levelData?.level ?? ''
    userTitle.value = levelData?.currentTitle || ''

    // 若未提供称号，再尝试获取一次称号列表
    if (!userTitle.value) {
      const titlesRes = await userLevelAPI.getUserTitles(uid, { meta: { silent: true } })
      const titlesData = (titlesRes && 'code' in titlesRes) ? handleApiResponse(titlesRes, 'data') : (titlesRes?.data || titlesRes)
      userTitle.value = Array.isArray(titlesData) ? (titlesData.find(t => t?.isCurrent)?.title || titlesData[0]?.title || '') : (titlesData?.currentTitle || '')
    }
  } catch (_) {}
}

// 统计：玩家总数与房间数量
const totalPlayers = computed(() => roomStore.roomStats.totalPlayers)
const roomsCount = computed(() => filteredRooms.value.length)

// 计算：过滤后的房间列表
const filteredRooms = computed(() => {
  const source = Array.isArray(roomStore.rooms) ? roomStore.rooms : []
  const query = searchQuery.value.trim().toLowerCase()
  if (!query) return source
  return source.filter(room =>
    String(room.roomName || '').toLowerCase().includes(query) ||
    String(room.roomId || '').toLowerCase().includes(query)
  )
})

// 响应式数据：弹窗状态
const searchQuery = ref('')
const showCreateRoom = ref(false)
const showJoinRoom = ref(false)
const pendingJoinRoomId = ref('')
// 房间信息弹窗已合并进成员弹窗
const showRoomMembers = ref(false)
const currentRoom = ref(null)

// 自动刷新定时器
let refreshTimer = null

// 加载房间列表
const loadRooms = async () => {
  try {
    await roomStore.fetchRoomList()
  } catch (error) {
    // ignore
  }
}

// 处理房间创建
const handleRoomCreated = async (roomData) => {
  try {
    // 直接使用API返回的数据，不需要再次调用createRoom
    showCreateRoom.value = false
    
    // 设置当前房间
    const roomId = roomData.id || roomData.roomId
    const roomName = roomData.roomName || roomData.name || '未命名房间'
    
    // 检查数据完整性
    if (!roomId) {}
    if (!roomName) {}
    
    currentRoom.value = {
      roomId: roomId,
      roomName: roomName,
      status: roomData.status?.toLowerCase() || 'waiting',
      playerCount: roomData.currentPlayers || 1, // 创建者自动加入
      maxPlayers: roomData.maxPlayers, // 使用传递过来的maxPlayers，不使用默认值
      creator: roomData.creator,
      playerNickname: roomData.playerNickname, // 保存玩家昵称
      createdAt: roomData.createdAt,
      startTime: roomData.startTime
    }
    
    // 先拉取一次房间详情（包含头像文件名），避免弹窗打开时头像为空
    try { await roomStore.fetchRoomInfo(roomId) } catch (_) {}

    // 连接 SignalR 并加入房间组（确保能收到广播）
    try {
      if (!socketManager.getConnectionStatus().isConnected) {
        await socketManager.connect() // 不需要传递token，会自动从localStorage获取
      }
      await socketManager.joinRoom(roomId, userStore.userDisplayName)
    } catch (e) {}

    // 显示房间成员弹窗
    showRoomMembers.value = true
    
    // 延迟刷新房间列表，避免重复显示
    setTimeout(() => {
      loadRooms()
    }, 1000)
  } catch (_) {}
}

// 处理加入房间
const handleRoomJoined = async (payload) => {
  try {
    const roomId = typeof payload === 'string' ? payload : payload?.roomId
    // 兼容旧参数结构（不再使用，仅为兼容保留）
    if (!roomId) { return }
    try {
      await roomStore.joinRoom(roomId)
    } catch (e) {
      // 如果已在其它房间，先尝试离开后再加入
      const msg = e?.response?.data?.message || e?.message || ''
      if (msg.includes('已经在房间')) {
        try {
          if (roomStore.currentRoom?.roomId && roomStore.currentRoom.roomId !== roomId) {
            await roomStore.leaveRoom(roomStore.currentRoom.roomId)
          }
          await roomStore.joinRoom(roomId)
        } catch {}
      } else {
        throw e
      }
    }
    showJoinRoom.value = false
    
    // 获取房间信息
    await roomStore.fetchRoomInfo(roomId)
    
    // 设置当前房间
    currentRoom.value = roomStore.currentRoom

    // 连接 SignalR 并加入房间组
    try {
      if (!socketManager.getConnectionStatus().isConnected) {
        await socketManager.connect() // 不需要传递token，会自动从localStorage获取
      }
      await socketManager.joinRoom(roomId, userStore.userDisplayName)
    } catch (e) {}
    
    // 显示房间成员弹窗
    showRoomMembers.value = true
  } catch (error) {
    // 忽略具体错误提示，由 store 统一处理
  }
}

// 旧的“房间信息加入”入口已内联到其他流程

// 卡片点击：直接进入房间流程（REST优先，失败再提示）
const enterRoomFromCard = async (room) => {
  const roomId = room?.roomId || room?.id
  if (!roomId) return

  // 若已经在该房间，直接打开准备界面
  if (roomStore.currentRoom?.roomId === roomId) {
    currentRoom.value = roomStore.currentRoom
    showRoomMembers.value = true
    return
  }

  try {
    // 如果在其他房间，确认是否切换
    if (roomStore.currentRoom?.roomId && roomStore.currentRoom.roomId !== roomId) {
      try {
        await ElMessageBox.confirm('你已在其它房间，是否离开并加入新的房间？', '切换房间', { type: 'warning' })
        await roomStore.leaveRoom(roomStore.currentRoom.roomId)
      } catch {
        return
      }
    }

    // 加入目标房间（REST）
    await roomStore.joinRoom(roomId)
    await roomStore.fetchRoomInfo(roomId)
    currentRoom.value = roomStore.currentRoom

    // 连接 SignalR 并加入房间组（兜底，不阻断流程）
    try {
      if (!socketManager.getConnectionStatus().isConnected) {
        await socketManager.connect() // 不需要传递token，会自动从localStorage获取
      }
      await socketManager.joinRoom(roomId, userStore.userDisplayName)
    } catch {}

    // 打开准备界面
    showRoomMembers.value = true
  } catch (_) {}
}

// 处理游戏开始（只负责跳转，不再重复触发开始逻辑）
const handleGameStarted = async (roomId) => {
  if (!roomId) return
  showRoomMembers.value = false
  try { router.push(`/game/${roomId}`) } catch (_) {}
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await userStore.logout()
    router.push('/login')
  } catch (_) {}
}

// 跳转到登录页面
const goToLogin = () => {
  router.push('/login')
}

// 启动自动刷新
const startAutoRefresh = () => {
  refreshTimer = setInterval(() => {
    loadRooms()
  }, 15000)
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 监听搜索查询变化
watch(searchQuery, () => {
  // 搜索时不需要额外处理，computed会自动过滤
})

// 页面加载时初始化
onMounted(async () => {
  await userStore.init()
  const tasks = [loadRooms(), loadAvatarUrl()]
  if (enableUserLevel) tasks.push(loadUserLevel())
  await Promise.all(tasks)
  
  // 初始化音频系统并播放大厅背景音乐
  const { useAudioStore } = await import('@/stores/audio')
  const audioStore = useAudioStore()
  audioStore.initAudio()
  
  // 播放大厅背景音乐 - 使用新的自动播放策略
  const musicSrc = '/audio/大厅背景音乐.mp3'
  
  // 使用新的自动播放策略
  console.log('🎵 使用新的自动播放策略...')
  try {
    await audioStore.playBackgroundMusic(musicSrc)
    console.log('🎵 背景音乐自动播放成功！')
  } catch (error) {
    console.log('🎵 自动播放失败，已设置用户交互监听器:', error.message)
    // 新的音频系统会自动处理用户交互，无需手动添加监听器
  }
  
  // 订阅大厅人数变化：动态更新房间卡片的 playerCount
  try {
    await socketManager.connect() // 不需要传递token，会自动从localStorage获取
  } catch (_) {}
  socketManager.on('RoomPlayerCountChanged', (data) => {
    const roomId = data?.roomId || data?.id
    const count = Number(data?.playerCount)
    if (!roomId || Number.isNaN(count)) return
    const idx = roomStore.rooms.findIndex(r => r.roomId === roomId)
    if (idx >= 0) roomStore.rooms[idx].playerCount = count
    if (roomStore.currentRoom?.roomId === roomId) {
      roomStore.currentRoom.playerCount = count
    }
  })
  
  // 若用户仍在某个房间（例如从游戏页返回大厅），自动打开房间成员弹窗
  const openMembersIfInRoom = async () => {
    try {
      const rid = roomStore.currentRoom?.roomId
      if (!rid) return
      // 拉取一次详情，保证成员、等级称号等信息最新
      try { await roomStore.fetchRoomInfo(rid) } catch (_) {}
      currentRoom.value = roomStore.currentRoom
      // 确保已加入 SignalR 房间组，以接收成员/准备状态等更新
      try {
        if (!socketManager.getConnectionStatus().isConnected) {
          await socketManager.connect()
        }
        await socketManager.joinRoom(rid, userStore.userDisplayName)
      } catch (_) {}
      showRoomMembers.value = true
    } catch (_) {}
  }
  await openMembersIfInRoom()
  startAutoRefresh()
})

// 页面卸载时清理
onUnmounted(async () => {
  stopAutoRefresh()
  if (avatarObjectUrl) URL.revokeObjectURL(avatarObjectUrl)
  
  // 清理音频资源
  const { useAudioStore } = await import('@/stores/audio')
  const audioStore = useAudioStore()
  audioStore.cleanup()
})
</script>

<style scoped>
.home-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */

/* 主布局 */
.main-layout {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 左侧边栏 */
.left-sidebar {
  width: 250px;
  background: white;
  border-right: 1px solid #e5e7eb;
  display: flex;
  flex-direction: column;
  padding: 20px;
  gap: 20px;
}



.refresh-btn {
  width: 30px;
  height: 30px;
  border: none;
  background: #f8fafc;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
  transition: all 0.2s ease;
}

.refresh-btn:hover:not(:disabled) {
  background: #eef2ff;
  border-color: #c7d2fe;
}

.refresh-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.refresh-icon {
  width: 16px;
  height: 16px;
}

/* 新的头部布局 */
.title-and-search { display: flex; gap: 14px; align-items: center; }
.title-and-search .search-wrap { min-width: 260px; width: 420px; }
.header-actions { display: flex; align-items: center; gap: 12px; }
.stat-pill { display: inline-flex; align-items: center; gap: 6px; padding: 6px 12px; border-radius: 999px; background: #f8fafc; border: 1px solid #e2e8f0; color: #334155; font-weight: 700; }
.stat-pill .icon { width: 14px; height: 14px; opacity: .9; }
.stat-pill.rooms { background: #eef2ff; border-color: #c7d2fe; color: #3730a3; }
.stat-pill.players { background: #ecfdf5; border-color: #a7f3d0; color: #065f46; }
.stat-pill .label { font-size: 12px; opacity: .8; }
.stat-pill .value { font-size: 14px; color: #111827; }

/* 个人信息区域 样式由 UserInfoCard 组件提供 */

/* 房间操作按钮区域 样式由 RoomActionButtons 组件提供 */



/* 房间列表样式 由 RoomGrid 和 RoomCard 组件提供 */

/* 右侧主内容区域 */
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  background: white;
  overflow-y: auto; /* Allow content to scroll */
}

.grid-wrap { margin-top: 12px; padding-top: 12px; border-top: 1px solid #e5e7eb; }

/* 提示条 */
.hint-box { display: inline-flex; align-items: center; gap: 10px; padding: 10px 12px; border-radius: 12px; border: 1px solid #e5e7eb; background: linear-gradient(180deg,#ffffff,#fafafa); box-shadow: 0 6px 14px rgba(2,6,23,.04); color: #0f172a; margin: 16px 0; }
.hint-icon { width: 28px; height: 28px; border-radius: 999px; background: #eef2ff; color: #3730a3; display: inline-flex; align-items: center; justify-content: center; box-shadow: inset 0 0 0 1px #c7d2fe; }
.hint-content { display: flex; flex-direction: column; }
.hint-title { font-weight: 800; font-size: 13px; color: #111827; }
.hint-text { font-size: 12px; color: #475569; }

/* 移动端自适应（小屏优化） */
@media (max-width: 640px) {
  .title-and-search {
    flex-direction: column;
    align-items: stretch;
    gap: 8px;
  }
  .title-and-search .search-wrap {
    width: 100%;
    min-width: 0;
  }
  .header-actions {
    justify-content: flex-start;
    flex-wrap: wrap;
    gap: 8px;
  }
  .stat-pill { padding: 6px 10px; }
  .stat-pill .label { font-size: 11px; }
  .stat-pill .value { font-size: 13px; }
  .refresh-btn { width: 28px; height: 28px; border-radius: 6px; }
  .refresh-icon { width: 14px; height: 14px; }
  .grid-wrap { margin-top: 10px; padding-top: 10px; }
}

.content-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.content-title {
  font-size: 20px;
  font-weight: 700;
  color: #374151;
  margin: 0;
}

.loading, .no-rooms {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100px;
  color: #6b7280;
  font-size: 14px;
}

/* 房间项目样式已移除，直接使用网格布局 */

/* Responsive adjustments */
@media (max-width: 768px) {
  .main-layout {
    flex-direction: column;
  }
  
  .left-sidebar {
    width: 100%;
    height: auto;
    max-height: 300px;
    overflow-y: auto;
  }

  .action-buttons {
    flex-direction: row;
    gap: 12px;
  }

  .action-btn {
    padding: 12px 16px;
    font-size: 14px;
  }

  /* 网格列数由 RoomGrid 控制 */

}

/* 大屏幕显示5列 */
@media (min-width: 1200px) {
  .room-grid {
    grid-template-columns: repeat(5, 1fr);
  }
}

/* 中等屏幕显示3列 */
@media (min-width: 768px) and (max-width: 1199px) {
  .room-grid {
    grid-template-columns: repeat(3, 1fr);
  }
}
</style>